from odoo import fields, models, api
from odoo.exceptions import UserError


class RPPostalCode(models.Model):
    _name = 'rp.postal.code'
    _description = '邮政编码'
    _sql_constraints = [('unique_name', 'UNIQUE(name,country_id,state_id,city_id)', '同一个国家、省份、市区下编码不能重复')]

    name = fields.Char(string='邮政编码', index=True, copy=False, required=True)

    country_id = fields.Many2one(string='国家', comodel_name='res.country', required=True)
    state_id = fields.Many2one(string='省', comodel_name='res.country.state', domain="[('country_id','=',country_id)]", required=True)
    city_id = fields.Many2one(string='市', comodel_name='res.city', domain="[('state_id','=',state_id)]", required=True)

    county_ids = fields.Many2many(string='区/县', comodel_name='res.county', domain="[('city_id','=',city_id)]",
                                  relation='rp_postal_code_and_county_rel', column1='postal_code_id', column2='county_id')

    level = fields.Selection(string='级别', selection=[('state', '省级'), ('city', '市级'), ('county', '区级')], default='city', help='用于处理邮编与省市区结构的联动')

    def name_get(self):
        result = []
        for record in self:
            name = record._get_name()
            result.append((record.id, name))
        return result


    def _get_name(self):
        name = self.name
        if self._context.get('show_city'):
            name = "%s - %s" % (self.name, self.city_id.name)
        return name


    @api.onchange('country_id')
    def _onchange_state(self):
        if self.state_id and (self.state_id.id not in self.country_id.state_ids.ids):
            self.state_id = False

    @api.onchange('state_id')
    def _onchange_state_id(self):
        if self.city_id and self.city_id.state_id != self.city_id:
            self.city_id = False

    @api.onchange('city_id')
    def _onchange_city_id(self):
        if self.county_ids:
            city_to_remove = self.county_ids.filtered(lambda s: s.city_id.id != self.city_id)
            self.county_ids -= city_to_remove

    @api.constrains('state_id', 'city_id', 'county_ids')
    def _fulfill_level(self):
        for s in self:
            if s.county_ids:
                s.write({'level': 'county'})
            elif s.city_id:
                s.write({'level': 'city'})
            elif s.state_id:
                s.write({'level': 'state'})

